;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Account.InvoiceInfo", [])
        .controller("InvoiceInfoCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            var btnPermissionCode = {
                invoiceInfoExport: window.ActionCode.invoiceExport,
                invoiceInfoEdit: window.ActionCode.invoiceEdit,
            };
            var invoiceNo = "";

            $scope.activeFlag = [true, false];
            $scope.btnPermission = {
                invoiceInfoExport: true,
                invoiceInfoEdit: true,
            };
            $scope.invoiceObj = "";
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.tableConfig = {
                scrollWidth: 1600,
                tableCol: [{
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 60,
                        isShow: true,
                        isFixed: true
                    },
                    {
                        name: "发票编号",
                        dataField: "invoiceNo",
                        width: 100,
                        toSort: false,
                        isShow: true,
                        type: "click",
                        clickFn: "viewDetail"
                    },
                    {
                        name: "客户编码",
                        dataField: "customerCode",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "客户名称",
                        dataField: "customerName",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "开票金额",
                        dataField: "amount",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "状态", // 0草稿，1已提交，2已完成
                        dataField: "status",
                        width: 100,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "是否邮寄", //0未邮寄，1已邮寄
                        dataField: "postFlag",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "是否开票", // 0未开票，1已开票
                        dataField: "billingFlag",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "客户是否需要发票", // 0否1是
                        dataField: "needFlag",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "纸质发票号",
                        dataField: "paperInvoiceNo",
                        width: 100,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "快递单号",
                        dataField: "trackingNo",
                        width: 100,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "创建人编号",
                        dataField: "createNo",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "创建人名称",
                        dataField: "createName",
                        width: 150,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "创建时间",
                        dataField: "createTime",
                        width: 130,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "修改人编号",
                        dataField: "updateNo",
                        width: 80,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "修改人名称",
                        dataField: "updateName",
                        width: 150,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "修改时间",
                        dataField: "updateTime",
                        width: 130,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "完成时间",
                        dataField: "finishTime",
                        width: 130,
                        toSort: false,
                        isShow: true
                    },
                    {
                        name: "公司orgId",
                        dataField: "orgId",
                        width: 130,
                        toSort: false,
                        isShow: true
                    }
                ]
            };
            $scope.dataList = [];
            $scope.toolbarConfig = {};
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/invoice/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/invoice/exportAll")
            };
            $scope.condition = {};

            $scope.changeTab = function (index) {
                angular.forEach($scope.activeFlag, function (activeFlag) {
                    activeFlag = false;
                });
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        break;
                    default:
                        break;
                }
            };


            /** 
             * 查询列表
             **/
            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };


            /** 
             * 配置表格列/高级搜索
             **/
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };


            /** 
             * 选择日期
             **/
            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.selectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };


            /** 
             * 点选列表字段查看详情
             **/
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function viewDetail(item) {
                invoiceNo = item.invoiceNo;
                getDetailDataList(1);
                $scope.changeTab(1);
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            function getDataList(curPage) {
                $scope.markInfo.curRow = -1;

                var service = "device",
                    reqUrl = "/swyInvoice/list",
                    param = {
                        pageSize: $scope.pageInfo.pageSize,
                        pageNum: $scope.pageInfo.curPage,
                        filters: angular.copy($scope.condition)
                    };

                if (!!curPage) {
                    param.pageNum = $scope.pageInfo.curPage = curPage;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.updateTime = $filter("YbDate")(item.orderDate, df);
                        item.finishTime = $filter("YbDate")(item.postDate, df);
                        item.createTime = $filter("YbDate")(item.signDate, df);
                        item.isChecked = false;
                        // item.signState = item.isSign === 1 ? "已签收" : "未签收";
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            /** 
             * 设置按钮权限
             **/
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function initData() {
                $scope.markInfo.allChecked = false;
                invoiceNo = "";
                $scope.detailPage.condition = {};
                $scope.detailPage.dataList = [];
            }


            /** 
             * 列表某条编辑
             **/
            $scope.edit = function (item) {
                $scope.invoiceObj = item;
                $scope.changeTab(2)
            };

            /*********************** 详情页开始 ***********************/
            $scope.detailPage = {};
            $scope.detailPage.markInfo = {
                curRow: -1
            };
            $scope.detailPage.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPage.condition = {};
            $scope.detailPage.dataList = [];
            $scope.detailPage.toolbarConfig = {};
            $scope.detailPage.tableConfig = {
                scrollWidth: 1960,
                tableCol: [{
                        name: "发票编号",
                        dataField: "invoiceId",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "发货通知单号",
                        dataField: "deliveryNoteNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "行号",
                        dataField: "rowNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "零件号",
                        dataField: "materialsNo",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "数量",
                        dataField: "qty",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "单价",
                        dataField: "price",
                        width: 170,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "总价",
                        dataField: "amount",
                        width: 145,
                        isShow: true,
                        toSort: false
                    },
                ]
            };

            $scope.detailPage.search = function (curpage) {
                getDetailDataList(curpage);
            };

            $scope.detailPage.reset = function () {
                $scope.detailPage.condition = {};
            };

            $scope.detailPage.switchToolbar = function (toolbar) {
                if (!!$scope.detailPage.toolbarConfig["show" + toolbar]) {
                    $scope.detailPage.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.detailPage.toolbarConfig["show" + toolbar] = true;
                });
            };

            $scope.detailPage.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.detailPage.selectRow = function (index) {
                $scope.detailPage.markInfo.curRow = index
            };


            function getDetailDataList(curPage) {
                $scope.detailPage.markInfo.curRow = -1;

                var service = "device",
                    reqUrl = "/swyInvoice/detailList",
                    param = {
                        pageSize: $scope.detailPage.pageInfo.pageSize,
                        pageNum: $scope.detailPage.pageInfo.curPage,
                        filters: angular.copy($scope.detailPage.condition)
                    };

                if (!!curPage) {
                    param.pageNum = $scope.detailPage.pageInfo.curPage = curPage;
                }

                param.filters.invoiceNo = invoiceNo;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    // 列表中数据格式的转换
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.updateTime = $filter("YbDate")(item.orderDate, df);
                        item.finishTime = $filter("YbDate")(item.postDate, df);
                        item.createTime = $filter("YbDate")(item.signDate, df);
                        item.isChecked = false;
                        // item.signState = item.isSign === 1 ? "已签收" : "未签收";
                    });
                    $scope.detailPage.pageInfo.totalRows = resp.value.total;
                    $scope.detailPage.pageInfo.totalPages = resp.value.pages;
                    $scope.detailPage.dataList = resp.value.list;
                });
            }

            /*********************** 详情页结束 ***********************/


            /**
             * ***************************************** 新增 开始 *****************************************
             */
            $scope.orderObj = {
                settleType: 0 // 新增列表上选择框是否已被勾选
            };


            /** 
             * 编辑页面：清空已选择的客户名称
             **/
            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.purchaseOrgId = data.dealerOrgId;
                    $scope.orderObj.purchaseOrgName = data.companyName; // 客户名称
                    $scope.orderObj.invoicePrice = data.invoicePrice; // 开票金额
                    getAddTableDataList();
                })
            };


            $scope.saveData = function (valid) {
                if (!valid || !$scope.orderObj.totalPrice || $scope.orderObj.totalPrice < 1) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/swyInvoice/update"; // 编辑开票
                var param = {};
                param.headerInfo = angular.copy($scope.orderObj);
                param.headerInfo.checkType = checkType;
                param.headerInfo.supplierOrgId = orgInfo.orgId;
                param.headerInfo.supplierOrgName = orgInfo.companyName;
                param.detailList = [];

                angular.forEach($scope.addTableInfo.dataList, function (item) {
                    if (item.isChecked) {
                        param.detailList.push({
                            // 新建传入的字段
                            invoiceNo: item.invoiceNo, // 发货通知单
                            billSingle: item.billSingle, // 行号
                            billId: item.billId, // 零件号
                            billDate: item.billDate, // 数量
                            checkPrice: item.checkPrice, // 单价
                            totalPrice: item.totalPrice, // 总价
                        });
                    }
                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };


            /* 新建页面上开票明细列表 */
            $scope.addTableInfo = {
                markInfo: {
                    allChecked: false,
                    curRow: -1
                },
                tableConfig: {
                    scrollWidth: 750,
                    tableCol: [{
                            name: "发票通知单",
                            dataField: "invoiceNo",
                            width: 140,
                            isShow: true,
                        },
                        {
                            name: "行号",
                            dataField: "billSingle",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "零件号", // wangcan：为什么没在列表中显示？
                            dataField: "billId",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "数量",
                            dataField: "billDate",
                            width: 130,
                            isShow: true
                        },
                        {
                            name: "单价",
                            dataField: "checkPrice",
                            width: 100,
                            isShow: true
                        },
                        {
                            name: "总价",
                            dataField: "totalPrice",
                            width: 100,
                            isShow: true
                        }
                    ]
                },
                dataList: [],
                /** 
                 * 开票明细列表排序
                 **/
                toSort: function (config, index) {
                    ybWidget.ToSort(config, index);
                },

                /** 
                 * 行选择
                 **/
                selectRow: function (index) {
                    $scope.addTableInfo.markInfo.curRow = index
                },

                /** 
                 * 新增开票明细列表全选
                 **/
                selectAll: function () {
                    for (var i = 0; i < $scope.addTableInfo.dataList.length; i++) {
                        $scope.addTableInfo.dataList[i].isChecked = $scope.addTableInfo.markInfo.allChecked;
                    }
                },
                /** 
                 * 新增开票明细列表
                 **/
                selectSingle: function (item) {
                    var selectAll = false;
                    if (!item.isChecked) {
                        selectAll = false;
                    } else {
                        selectAll = checkAll($scope.addTableInfo.dataList);
                    }
                    $scope.addTableInfo.markInfo.allChecked = selectAll;
                },
            };

            function getAddTableDataList() {
                $scope.addTableInfo.markInfo.curRow = -1;
                $scope.addTableInfo.markInfo.allChecked = false;
                var service = "device",
                    reqUrl = "/arap/detailList",
                    param = {
                        filters: {
                            orgId: $scope.orderObj.purchaseOrgId,
                            type: 0,
                            isSettle: 0,
                            isAll: 1
                        }
                    };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.addTableInfo.dataList = resp.value.list;
                });
            }

            /**
             * ***************************************** 新增 结束 *****************************************
             */


            (function () {
                if ($scope.isZHJCH) {
                    var newTableConfig = angular.copy($scope.tableConfig);
                    $scope.tableConfig.scrollWidth = 1540;
                    $scope.tableConfig.tableCol = [];
                    angular.forEach(newTableConfig.tableCol, function (item) {
                        if (item.type !== 'operate') {
                            $scope.tableConfig.tableCol.push(angular.copy(item));
                        }
                    });
                }

                getDataList(1);
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);